package com.pms.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pms.config.LocationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class LocationUtils {
    @Autowired
    private LocationConfig amapConfig;

    private static final String GEOCODE_URL = "https://restapi.amap.com/v3/geocode/regeo";

    /**
     * 计算两个坐标点之间的距离(米)
     */
    public double calculateDistance(double lat1, double lng1, double lat2, double lng2) {
        final double EARTH_RADIUS = 6371000; // 地球半径(米)

        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double deltaLat = Math.toRadians(lat2 - lat1);
        double deltaLng = Math.toRadians(lng2 - lng1);

        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                Math.cos(radLat1) * Math.cos(radLat2) *
                        Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return EARTH_RADIUS * c;
    }

    /**
     * 根据经纬度获取地址信息
     */
    public String getAddress(double latitude, double longitude) {
        String url = String.format("%s?key=%s&location=%f,%f",
                GEOCODE_URL, amapConfig.getKey(), longitude, latitude);

        try {
            // 使用RestTemplate或其他HTTP客户端调用高德API
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject(url, String.class);

            // 解析响应JSON，获取地址信息
            JSONObject jsonObject = JSON.parseObject(response);
            if ("1".equals(jsonObject.getString("status"))) {
                JSONObject regeocode = jsonObject.getJSONObject("regeocode");
                return regeocode.getString("formatted_address");
            }
        } catch (Exception e) {
            log.error("获取地址信息失败", e);
        }
        return null;
    }

    /**
     * 验证打卡位置是否在允许范围内
     */
    public boolean isWithinWorkplace(double latitude, double longitude) {
        double distance = calculateDistance(
                latitude, longitude,
                amapConfig.getWorkplaceLatitude(),
                amapConfig.getWorkplaceLongitude()
        );
        return distance <= amapConfig.getAllowedDistance();
    }
}